// final_test.js
const http = require('http');
const fs = require('fs');
const path = require('path');

console.log('=== 淘宝采购订单数据处理测试 ===\n');

// 1. 读取淘宝进货单数据文件
console.log('1. 读取淘宝进货单数据文件...');
const taobaoDataFilePath = path.join(__dirname, '通过插件拦截响应数据（淘宝进货单）.md');
const taobaoData = fs.readFileSync(taobaoDataFilePath, 'utf8');
const jsonData = JSON.parse(taobaoData);
console.log('   ✓ 数据文件读取成功\n');

// 2. 配置请求选项
console.log('2. 配置API请求...');
const options = {
  hostname: '127.0.0.1',
  port: 9001,
  path: '/api/v1/plugin/data/receive',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
  }
};
console.log('   ✓ 请求配置完成\n');

// 3. 发送请求到API端点
console.log('3. 发送数据到API端点...');
const req = http.request(options, (res) => {
  console.log(`   ✓ 服务器响应状态码: ${res.statusCode}`);
  
  let responseData = '';
  
  res.on('data', (chunk) => {
    responseData += chunk;
  });
  
  res.on('end', () => {
    console.log('   ✓ 服务器响应接收完成');
    
    try {
      const result = JSON.parse(responseData);
      if (result.code === 0) {
        console.log('   ✓ 数据发送成功！');
        console.log(`   ✓ 接收数量: ${result.data.receivedCount}`);
        console.log(`   ✓ 处理数量: ${result.data.processedCount}`);
        console.log(`   ✓ 批次ID: ${result.data.batchId}`);
        
        // 4. 验证数据库中的数据
        console.log('\n4. 验证数据库中的数据...');
        setTimeout(() => {
          const { Sequelize, DataTypes } = require('sequelize');
          
          // 数据库配置
          const config = {
            dialect: 'mysql',
            host: '127.0.0.1',
            port: 3306,
            database: 'lingxi_system',
            username: 'root',
            password: '888mei525',
            timezone: '+08:00',
            define: {
              charset: 'utf8mb4',
              dialectOptions: {
                collate: 'utf8mb4_unicode_ci',
              },
              timestamps: true,
            },
          };
          
          // 创建Sequelize实例
          const sequelize = new Sequelize(config.database, config.username, config.password, config);
          
          // 定义采购订单模型
          const PurchaseOrder = sequelize.define('purchase_order', {
            id: {
              type: DataTypes.INTEGER,
              primaryKey: true,
              autoIncrement: true
            },
            orderNumber: {
              type: DataTypes.STRING(50),
              allowNull: false,
              unique: true,
              field: 'order_number'
            },
            supplierId: {
              type: DataTypes.INTEGER,
              allowNull: false,
              field: 'supplier_id'
            },
            purchaser: {
              type: DataTypes.STRING(50),
              allowNull: true
            },
            orderDate: {
              type: DataTypes.DATE,
              allowNull: false,
              field: 'order_date'
            },
            expectedDeliveryDate: {
              type: DataTypes.DATE,
              allowNull: true,
              field: 'expected_delivery_date'
            },
            totalAmount: {
              type: DataTypes.DECIMAL(15, 2),
              allowNull: false,
              field: 'total_amount'
            },
            status: {
              type: DataTypes.STRING(20),
              defaultValue: 'pending',
              allowNull: false
            },
            remark: {
              type: DataTypes.TEXT,
              allowNull: true
            },
            organizationId: {
              type: DataTypes.INTEGER,
              allowNull: false,
              field: 'organization_id'
            }
          }, {
            tableName: 'purchase_orders',
            timestamps: true,
            createdAt: 'created_at',
            updatedAt: 'updated_at'
          });
          
          // 定义采购订单项模型
          const PurchaseOrderItem = sequelize.define('purchase_order_item', {
            id: {
              type: DataTypes.INTEGER,
              primaryKey: true,
              autoIncrement: true
            },
            orderId: {
              type: DataTypes.INTEGER,
              allowNull: false,
              field: 'order_id'
            },
            productId: {
              type: DataTypes.INTEGER,
              allowNull: true,
              field: 'product_id'
            },
            productName: {
              type: DataTypes.STRING(100),
              allowNull: false,
              field: 'product_name'
            },
            specification: {
              type: DataTypes.STRING(100),
              allowNull: true
            },
            quantity: {
              type: DataTypes.INTEGER,
              allowNull: false
            },
            unit: {
              type: DataTypes.STRING(20),
              allowNull: true
            },
            unitPrice: {
              type: DataTypes.DECIMAL(15, 2),
              allowNull: false,
              field: 'unit_price'
            },
            amount: {
              type: DataTypes.DECIMAL(15, 2),
              allowNull: false
            },
            remark: {
              type: DataTypes.STRING(200),
              allowNull: true
            }
          }, {
            tableName: 'purchase_order_items',
            timestamps: true,
            createdAt: 'created_at',
            updatedAt: 'updated_at'
          });
          
          // 查询数据
          async function checkData() {
            try {
              await sequelize.authenticate();
              console.log('   ✓ 数据库连接成功');
              
              // 查询采购订单数据
              const orderCount = await PurchaseOrder.count();
              const orderItemCount = await PurchaseOrderItem.count();
              
              console.log(`   ✓ 采购订单总数: ${orderCount}`);
              console.log(`   ✓ 采购订单项总数: ${orderItemCount}`);
              
              if (orderCount > 0 && orderItemCount > 0) {
                console.log('\n=== 测试结果 ===');
                console.log('✅ 恭喜！淘宝采购订单数据处理功能测试成功！');
                console.log('✅ 数据已成功从插件接收并保存到数据库中');
                console.log('✅ purchase_orders 表和 purchase_order_items 表都有数据');
              } else {
                console.log('\n=== 测试结果 ===');
                console.log('❌ 测试失败：数据库中没有找到相关数据');
              }
            } catch (error) {
              console.error('   ❌ 数据库查询出错:', error.message);
            } finally {
              await sequelize.close();
            }
          }
          
          checkData();
        }, 2000); // 等待2秒确保数据处理完成
      } else {
        console.log('   ❌ 数据发送失败:', result.message);
      }
    } catch (e) {
      console.log('   ❌ 响应解析失败:', responseData);
    }
  });
});

req.on('error', (error) => {
  console.error('   ❌ 请求出错:', error.message);
});

// 发送数据
req.write(JSON.stringify(jsonData));
req.end();

console.log('   ✓ 请求已发送，请等待响应...\n');